<template>
  <el-dialog
    class="addedit-invoice-dialog"
    width="600px"
    :visible.sync="dialogVisible"
    :title="operType == 'add' ? '新增发票抬头' : '修改发票抬头'"
    :close-on-click-modal="false"
    v-dialogDrag="true"
    @open="handleDialogOpen"
    @closed="handleDialogClosed"
  >
    <el-form ref="addEditInvoiceForm" :model="formData" :rules="formRules" size="small" label-width="130px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="客户名称:" prop="entrustOrganizationId">
            <OrganizationSelect
              style="width: 100%;"
              ref="clientOrganizationSelect"
              v-model="formData.entrustOrganizationId"
              @change="(value, option) => {
                formData.companyName = option ? option.organizationName : '';
                handleSelectClientOrganization(value, option);
              }"
            ></OrganizationSelect>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="发票抬头名称:" prop="companyName">
            <el-input v-model="formData.companyName" placeholder="请输入" clearable>
              <el-button :disabled="disableQCCheck" slot="append" @click="handleInvoiceHeaderName"><svg-icon icon-class="qcc" class="qcc" /></el-button>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="税号:" prop="taxId">
            <el-input v-model="formData.taxId" placeholder="请输入" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="开户行:" prop="openBank">
            <el-input v-model="formData.openBank" placeholder="请输入" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="开户银行支行名称:" prop="openBankBranch">
            <el-input v-model="formData.openBankBranch" placeholder="请输入" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="银行账号:" prop="bankAccount">
            <el-input v-model="formData.bankAccount" placeholder="请输入" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="联系电话:" prop="contactNumber">
            <el-input v-model="formData.contactNumber" placeholder="请输入" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="地址:" prop="address">
            <el-input v-model="formData.address" placeholder="请输入" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- <el-row>
        <el-col :span="24">
          <el-form-item label="附件:" prop="attachment">
            <el-upload
              ref="attachmentUploadRef"
              :action="uploadParams.url"
              :headers="uploadParams.headers"
              :before-upload="handleBeforeUpload"
              :on-success="handleSuccessFile"
              :on-error="handleErrorFile"
              :on-remove="handleRemoveFile"
              :on-preview="handlePreviewFile"
              :file-list="attachmentFileList"
              multiple
            >
              <el-button icon="el-icon-upload" size="mini" plain type="primary">添加附件</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row> -->
    </el-form>

    <div class="dialog-footer" slot="footer">
      <el-button style="margin-right: 50px;" type="primary" @click="handleSave">保存</el-button>
      <el-button @click="dialogVisible = false">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  invoiceDetail,
  invoiceAdd,
  invoiceEdit,
  invoiceDetailByOrganizationId
} from '@/api/person/invoice'
import { entrustOrganizationDetail } from '@/api/person/entrustOrganization'
import { qcc } from '@/api/person/invoicing'
import { getToken } from '@/utils/auth'

export default {
  name: 'AddEditInvoiceDialog',
  components: {},
  dicts: [],
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    operType: {
      type: String,
      default: 'add',
    },
    row: {
      type: Object,
      default: () => ({})
    },
  },
  computed: {
    dialogVisible: {
      get() {
        return this.show
      },
      set(value) {
        this.$emit('update:show', value)
      }
    },
    disableQCCheck() {
      return !!this.formData.taxId
    },
  },
  data() {
    return {
      formData: {},
      formRules: {
        entrustOrganizationId: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        companyName: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        taxId: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        openBank: [
          { required: false, message: '请输入', trigger: 'blur' }
        ],
        openBankBranch: [
          { required: false, message: '请输入', trigger: 'blur' }
        ],
        bankAccount: [
          { required: false, message: '请输入', trigger: 'blur' }
        ],
        contactNumber: [
          { required: false, message: '请输入', trigger: 'blur' }
        ],
        address: [
          { required: false, message: '请输入', trigger: 'blur' }
        ],
        // attachment: [],
      },
      // 文件上传参数
      uploadParams: {
        url: process.env.VUE_APP_BASE_API + '/system/oss/upload',
        headers: {
          Authorization: 'Bearer ' + getToken(),
          'Content-Disposition': 'inline',
        },
      },
      attachmentFileList: [],
    }
  },
  created() {
    this.initFormData()
  },
  methods: {
    // 弹框打开时
    handleDialogOpen() {
      if (this.operType == 'edit') {
        invoiceDetail(this.row.invoiceHeaderId).then(res => {
          for (let key in this.formData) {
            this.formData[key] = res.data[key]
          }
          // this.attachmentFileList = JSON.parse(res.data.attachment || '[]')
        }).catch(err => {})
        this.$nextTick(() => {
          this.$refs['clientOrganizationSelect'].setDefaultOption({
            entrustOrganizationId: this.row.entrustOrganizationId,
            organizationName: this.row.entrustOrganizationName
          })
        })
      }
    },
    // 弹框关闭时
    handleDialogClosed() {
      this.initFormData()
      this.$refs.addEditInvoiceForm.resetFields()
      this.attachmentFileList = []
    },
    // 初始化表单数据
    initFormData() {
      this.formData = {
        entrustOrganizationId: '',
        companyName: '',
        taxId: '',
        openBank: '',
        openBankBranch: '',
        bankAccount: '',
        contactNumber: '',
        address: '',
        // attachment: '',
      }
    },
    // 获取表单数据
    getFormData() {
      const data = JSON.parse(JSON.stringify(this.formData))
      // data.attachment = JSON.stringify(this.attachmentFileList.map(item => ({
      //   ossId: item.response?.data.ossId || item.ossId,
      //   url: item.response?.data.url || item.url,
      //   name: item.response?.data.name || item.name
      // })))
      if (this.operType == 'edit') {
        data.invoiceHeaderId = this.row.invoiceHeaderId
      }
      return data
    },
    // 点击保存
    handleSave() {
      this.$refs.addEditInvoiceForm.validate(valid => {
        if (!valid) return
        let fn = null
        if (this.operType == 'add') fn = invoiceAdd
        else if (this.operType == 'edit') fn = invoiceEdit
        const data = this.getFormData()
        fn(data).then(res => {
          this.$message.success('操作成功')
          this.dialogVisible = false
          this.$emit('refresh')
        }).catch(err => {})
      })
    },

    // 文件上传前
		handleBeforeUpload(file) {
			// let isPDF = (file.type === 'application/pdf')
			// if (!isPDF) {
			// 	this.$message.warning('仅支持pdf格式，请重新上传!')
			// }
			// return isPDF
      return true
		},
    // 文件上传成功
    handleSuccessFile(res, file, fileList) {
			if (res.code == 500) {
				return this.$message.error(res.msg)
			}
			this.attachmentFileList = fileList
    },
    // 文件上传失败
    handleErrorFile(err, file, fileList) {
      this.$message.error('文件上传失败')
    },
    // 移除文件
    handleRemoveFile(file, fileList) {
      this.attachmentFileList = fileList
		},
    // 预览文件
    handlePreviewFile(file, fileList) {
			if (file.response && file.response.data) {
				window.open(file.response.data.url, 'PDF', '')
			} else if (file.url) {
				window.open(file.url, 'PDF', '')
			}
		},
    // 查询企业信息
    handleInvoiceHeaderName() {
      if(this.formData.companyName) {
        qcc({keyWord:this.formData.companyName}).then(res => {
          this.$set(this.formData, 'taxId', res.data.creditCode);
          this.$set(this.formData, 'openBank', res.data.bank);
          this.$set(this.formData, 'bankAccount', res.data.bankAccount);
          this.$set(this.formData, 'contactNumber', res.data.tel);
          this.$set(this.formData, 'address', res.data.address);
        })
      }
    },
    handleSelectClientOrganization(val) {
      entrustOrganizationDetail(val).then(res=>{
        if(res.data.unifiedCreditCode) {
          this.$set(this.formData, 'taxId', res.data.unifiedCreditCode);
        } else {
          invoiceDetailByOrganizationId(val).then(response=>{
            this.$set(this.formData, 'taxId', response.data?.taxId || '');
          })
        }
      })
    }
  },
}
</script>

<style lang="scss" scoped>
.addedit-invoice-dialog {

  ::v-deep .el-dialog__body {
    max-height: 70vh;
    overflow-y: auto;
  }

  .line-1 ::v-deep .el-form-item__label {
    line-height: 1;
  }
}
.qcc {
  width: 20px;
  height: 20px;
}
</style>
